package echo.demo;

import echo.codec.RpcDecoder;
import echo.codec.RpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Client {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
//                        pipeline.addLast(new MessageDecoder());
//                        pipeline.addLast(new MessageEncoder());
                        pipeline.addLast(new RpcDecoder(StudentDto.class));
                        pipeline.addLast(new RpcEncoder(StudentDto.class));
                        pipeline.addLast(new ClientHandler());
                    }
                });
        ChannelFuture f = bootstrap.connect("localhost", 8000).sync();
        Channel channel = f.channel();
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        abc(channel, executorService);
        Thread.sleep(3000);
        abc(channel, executorService);
        f.channel().closeFuture().sync();
    }

    private static void abc(Channel channel, ExecutorService executorService) {
        HashMap<Integer, Object> map = new HashMap<>();
        for (int i = 0; i < 100; i++) {
            map.put(i, "asdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdf");
        }
        for (int i = 0; i < 100000; i++) {
            int finalI = i;
            executorService.submit(() -> {
                StudentDto studentDto = new StudentDto();
                studentDto.setId(finalI);
                studentDto.setName("zpy" + finalI+ " "+ Thread.currentThread().getName());
                studentDto.setMap(map);
                channel.writeAndFlush(studentDto);
            });
        }
    }
}
